package mao.thinkinjava.concurency.exchanger;

import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.concurrent.Exchanger;

/**
 * @author Totoro
 * @date 2020/6/2
 * @explain:
 */
public class ExchangeConsumer<T> implements Runnable {
    private Exchanger<List<T>> exchanger;
    private List<T> holder;

    public ExchangeConsumer(Exchanger<List<T>> exchanger,List<T> holder) {
        this.exchanger = exchanger;
        this.holder = holder;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()){
            try {
                holder = exchanger.exchange(holder);
                for(T t : holder){
                    System.out.println("consumer "+t);
                    holder.remove(t);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().interrupt();//重新设置中断标志位。
            } catch (ConcurrentModificationException e){

            }
        }
    }
}
